<?php

namespace App\Kuafu\Order\Service;

use App\Kuafu\Base\Service\BaseService;
use App\Kuafu\CouponExt\Enum\CouponExtEnum;
use App\Kuafu\CouponExt\Model\OrderCouponExtSplitModel;
use App\Kuafu\Order\Enum\CodeEnum;
use App\Kuafu\Order\Model\OrderCouponSplitModel;
use App\Kuafu\Order\Model\OrderDetailSplitModel;
use App\Kuafu\Order\Model\OrderSplitModel;
use Illuminate\Support\Facades\Redis;
use \Illuminate\Redis\Connections\Connection;

/**
 * 订单操作基础服务
 *
 * Class OrderOperateService
 * @package App\Kuafu\Order\Service
 */
class OrderBaseSplitService extends BaseService
{
    /**
     * @var string OrderId
     */
    public string $orderId = '';

    protected Connection $redisConnect;

    /**
     * 获取订单 ID
     *
     * @return string
     */
    public function getOrderId(bool $isInt = false)
    {
        if ($isInt) {
            return (int)$this->orderId;
        } else {
            return (string)$this->orderId;
        }
    }

    /**
     * @var object  主订单详情
     */
    public ?object $orderInfo = null;

    public function __construct($brandId = 0, $shopId = 0, $orderId = '')
    {
        parent::__construct($brandId, $shopId);
        if (!empty($orderId)) {
            $this->orderId   = strval($orderId);
            $this->orderInfo = OrderSplitModel::suffix($shopId)->query()->where('orderId', (int)$this->getOrderId(true))
                                              ->first();
        }

        $this->redisConnect = Redis::connection();
    }

    /**
     * 获取订单详情
     *
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public function getOrderInfo(bool $refresh = false)
    {
        return $refresh ? OrderSplitModel::suffix($this->shopId)->query()->where('orderId', $this->getOrderId(true))
                                         ->first() : $this->orderInfo;
    }

    /**
     * @var array 获取订单详情
     */
    private static array $orgDetail = [];

    public function getOrderDetail(bool $refresh = false): array
    {
        if (empty(self::$orgDetail[$this->orderId]) || $refresh) {
            $orderDetail = OrderDetailSplitModel::suffix($this->shopId)->query()
                                                ->where('orderId', $this->getOrderId(true))
                                                ->get();

            self::$orgDetail[$this->orderId] = $orderDetail->toArray() ?? [];
        }
        return self::$orgDetail[$this->orderId];
    }

    /**
     * @var array 获取原订单的三方优惠券信息
     */
    private static array $orgExtCoupon = [];

    public function getOrderExtCoupon(
        bool $refresh = false,
        int $couponExtStatus = CouponExtEnum::COUPON_STATUS_USED
    ): array {
        if (empty(self::$orgExtCoupon[$this->orderId][$couponExtStatus]) || $refresh) {

            $list = OrderCouponExtSplitModel::suffix($this->shopId)
                                            ->query()
                                            ->where('orderId', $this->getOrderId(true))
                                            ->where('couponExtStatus', $couponExtStatus)
                                            ->get();

            self::$orgExtCoupon[$this->orderId][$couponExtStatus] = $list->toArray() ?? [];

        }
        return self::$orgExtCoupon[$this->orderId][$couponExtStatus];
    }


    /**
     * @var array 获取订单使用的内部优惠券
     */
    private static array $orgCoupon = [];

    public function getOrderCoupon(
        bool $refresh = false,
        int $status =CouponExtEnum::COUPON_STATUS_USED
    ): array {
        if (empty(self::$orgCoupon[$this->orderId][$status]) || $refresh) {

            $list = OrderCouponSplitModel::suffix($this->shopId)->query()->where('orderId', $this->orderId)
                                         ->where('status', $status)
                                         ->get();

            self::$orgCoupon[$this->orderId][$status] = $list->toArray() ?? [];

        }
        return self::$orgCoupon[$this->orderId][$status];
    }


    /**
     * 订单上锁
     * @param int $time
     * @param string $tag
     * @return mixed
     */
    public function lockOrder($time = 0, $tag = CodeEnum::ORDER_LOCK_TYPE_RESERVE)
    {
        $key    = $this->getOrderLockPayKey($tag);
        $return = Redis::setNx($key, 'locked');
        if ($return) {
            Redis::expire($key, $time);
        }

        return $return;
    }

    /**
     * 解锁订单
     * @param string $tag
     * @return mixed
     */
    public function unLockOrder($tag = CodeEnum::ORDER_LOCK_TYPE_RESERVE)
    {
        $key    = $this->getOrderLockPayKey($tag);
        $return = Redis::del($key);

        return $return;
    }

    /**
     * 获取订单上锁时间
     * @param string $tag
     * @return mixed
     */
    public function getLockTime($tag = CodeEnum::ORDER_LOCK_TYPE_RESERVE)
    {
        $key    = $this->getOrderLockPayKey($tag);
        $return = Redis::ttl($key);

        return $return;
    }

    /**
     * 获取锁单的 key
     * @return string
     */
    public function getOrderLockPayKey($tag = 'reserve')
    {
        return 'REDIS:LOCK_ORDER:' . $tag . ':' . $this->brandId . '_' . $this->shopId . ':' . $this->orderId;
    }

    /**
     * 更新订单状态
     *
     * @param $orderStatus
     */
    public function updateOrderStatus($orderStatus)
    {
        $this->orderInfo->orderStatus = $orderStatus;
        $this->orderInfo->save();
    }
}
